package com.lishe.lishe.retrofit.presenter;

import android.util.ArrayMap;
import android.util.Log;

import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.utils.FileUtils;
import com.lishe.lishe.retrofit.BaseRequestBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.MyObserver.FileUploadObserver;
import com.lishe.lishe.retrofit.MyRequestBody.UploadFileRequestBody;
import com.lishe.lishe.retrofit.RetrofitFactory;
import com.lishe.lishe.retrofit.bean.UploadInfo;
import com.lishe.lishe.retrofit.interfaces.FileService;
import com.lishe.lishe.retrofit.interfaces.ProgressListener;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by DELL on 2017/11/22.
 */

public class FilePresenter {
    private static final String upFile = "lshe.framework.excitation/api/appEncourage/uploadFile";//上传文件
    public static final String URL = Globals.LISHE_URL_EXCITATION + upFile;
    private static FilePresenter filePresenter;

    private FilePresenter() {

    }

    public static FilePresenter getInstance() {
        if (filePresenter == null) {
            filePresenter = new FilePresenter();
        }
        return filePresenter;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param token
     * @param fileUploadObserver
     * @return
     */
    public void upload(File file, byte[] buff, String token, FileUploadObserver<BaseRequestBody<UploadInfo>> fileUploadObserver) {
        FileService fileService = RetrofitFactory.createExcitationUrl().create(FileService.class);
        UploadFileRequestBody body = null;
        String fileName = null;
        if (file != null) {
            body = new UploadFileRequestBody(file, fileUploadObserver);
            fileName = file.getName() + ".jpg";
        }
        if (buff != null) {
            body = new UploadFileRequestBody(buff, fileUploadObserver);
            fileName = "img.jpg";
        }

        MultipartBody.Part part = MultipartBody.Part.createFormData("imgFile1", fileName, body);
        RequestBody tokenBody = RequestBody.create(MediaType.parse("multipart/form-data"), token);

        fileService.uploadFile(URL, tokenBody, part)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fileUploadObserver);
    }

    /**
     * 下载并保存文件
     *
     * @param filePath             保存文件路径
     * @param fileName             保存文件名称
     * @param dataResponseListener
     */
    public void downLoad(final File filePath, final String fileName, final DataResponseListener dataResponseListener) {
        ProgressListener listener = new ProgressListener() {
            @Override
            public void onProgress(long progress, long total, boolean done) {
                dataResponseListener.onProgress(progress, total, done);
            }
        };

        RetrofitFactory.createDownloadUrl(listener).create(FileService.class)
                .downLoadFile()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.e("TAG", "onSubscribe ");
                        dataResponseListener.onPrepare();
                    }

                    @Override
                    public void onNext(@NonNull ResponseBody responseBody) {
                        Log.e("TAG", "responseBody contentLength = " + responseBody.contentLength());
                        final InputStream is = responseBody.byteStream();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean isSaveSuccess = FileUtils.saveFile(is, filePath, fileName);
                                if (isSaveSuccess) {
                                    dataResponseListener.onSuccess(new File(filePath,fileName).getAbsolutePath());
                                } else {
                                    dataResponseListener.onFail("保存失败！");
                                }
                            }
                        }).start();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("TAG", "onError " + e.toString());
                        dataResponseListener.onError(e);
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG", "onComplete ");
                    }
                });

    }
}
